package com.qianchang.microfinance.view.credit.data;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;

import com.dm.library.utils.DMLog;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.event.PhoneAuthEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.hsdialog.CommunicationServiceDialog;
import com.rong360.app.crawler.CrawlerCallBack;
import com.rong360.app.crawler.CrawlerManager;
import com.rong360.app.crawler.CrawlerStatus;
import com.rong360.app.crawler.Util.CommonUtil;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by SSC on 2017/12/27.
 *
 *  手机认证
 *
 */

public class PhoneAuthActivity extends BaseActivity{

    private String file;
    @BindView(R.id.ck_protocol)
    CheckBox cbProtocol;
    @BindView(R.id.tv_protocol)
    DTextView tvProtocol;

    private String mPrivateKey;
    private FindUserBasicInfoBean basicInfoBean;
    private String phoneNub;
    private String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phoneauth_layout);
        ButterKnife.bind(this);

        initView();
        initData();
        initCrawlerConfig();            //
        startCrawlerTask("mobile");
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    private boolean isConfirml = false;

    @Override
    protected void initView() {
        super.initView();

        setTitle("手机验证");
        phoneNub = DMApplication.getInstance().getmUserLoginInfo().getPhone();
        userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();

        Bundle bundle = getBundle();
        if (null != bundle) {
            isConfirml = bundle.getBoolean("isConfirml",false);
            basicInfoBean = (FindUserBasicInfoBean) bundle.getSerializable(ConstantAppInfo.BASIC_INFO_BEAN);
            if (null != basicInfoBean) {
                refreshView();
            }
        }
        if (basicInfoBean == null) {
            basicInfoBean = new FindUserBasicInfoBean();
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    private void refreshView() {
        switch (basicInfoBean.getIsIdCardCheckThrough()) {
            case 0:

                break;
            case 1:

                break;
            default:
                break;
        }
    }


    @OnClick({R.id.bt_next_id,R.id.tv_msgforgetpsw_id})
    public void onViewClicked(View view){
        switch (view.getId()) {
            case R.id.bt_next_id:

                startActivity(PhoneAuthMsgCodeActivity.class,true);

                break;
            case R.id.tv_msgforgetpsw_id:

                CommunicationServiceDialog.newInstance().show(getSupportFragmentManager(), "commdialog");

                break;
            default:
                break;
        }
    }


    /**
     * 配置融360天机手机抓取SDK
     */
    private void initCrawlerConfig() {
        mPrivateKey = CommonUtil.getFromAssets("rsa.cer");
        CrawlerManager.getInstance().setDebug(false);      //打开debug
    }

    /**
     * 该方法为抓取的通用样例代码
     *
     * @param module 抓取目标模块名
     */
    private void startCrawlerTask(String module) {
        try{
            show("数据加载中....");
            CrawlerStatus crawlerStatus = new CrawlerStatus();
            crawlerStatus.type = module;
            crawlerStatus.taskid = String.valueOf(System.currentTimeMillis());
            crawlerStatus.appname = "com.qianchang.microfinance";           //自定义name，可以传包名
            crawlerStatus.privatekey = mPrivateKey;                         //天机分配的私钥
            crawlerStatus.merchant_id = DMConstant.Rong360.appid;           //添加分配的appid


            //以下为身份信息三要素，必传
            crawlerStatus.real_name = basicInfoBean.getRealName();//姓名
            crawlerStatus.id_card = basicInfoBean.getIdCard().toString().trim();//身份证
//        crawlerStatus.id_card = "450923198510133510";//身份证
            crawlerStatus.cellphone = phoneNub ;//手机

            //如果机构后端需要收到三要素透传，请增加如下代码
            crawlerStatus.obtainExtraParams().put("userPhone",phoneNub);
            crawlerStatus.obtainExtraParams().put("userIdCard", basicInfoBean.getIdCard());
            crawlerStatus.obtainExtraParams().put("userName", basicInfoBean.getRealName());
            crawlerStatus.obtainExtraParams().put("userId", userId);

            CrawlerManager.getInstance().startCrawlerByType(new CrawlerCallBack() {
                @Override
                public void onStatus(CrawlerStatus crawlerStatus) {

                    getStringStatus(crawlerStatus.status);

                }
            }, crawlerStatus);

        }catch (Exception e){
            e.printStackTrace();
        }

    }


    private void getStringStatus(int status) {
        dismiss();
        String text = null;
        switch (status) {
            case 0:
                text = "未初始化";
                ToastUtil.getInstant().show(getApplicationContext(),"初始化失败");
                EventBus.getDefault().post(new PhoneAuthEvent(PhoneAuthEvent.PhoneAuthStatue.PHONEAUTH_INITIALIZE));
                PhoneAuthActivity.this.finish();
                break;
            case 1:
                text = "抓取开始";
                DMLog.e("抓取开始");
                EventBus.getDefault().post(new PhoneAuthEvent(PhoneAuthEvent.PhoneAuthStatue.PHONEAUTH_START_CRAWLING));


                break;
            case 2:
                DMLog.e("登录成功");
                DMLog.e("验证中");
                EventBus.getDefault().post(new PhoneAuthEvent(PhoneAuthEvent.PhoneAuthStatue.PHONEAUTH_LOGIN_SUS));

                if(isConfirml){
                    show("验证中....");
                    PhoneAuthActivity.this.finish();
                }else {
                    if (basicInfoBean.getIsTongDunAuth() != 0) {
                        startActivity(GoSesameAuthorizedActivity.class, true);           //如果同盾未认证过，走芝麻认证里面的同盾认证接口
                        return;
                    }
                    if (basicInfoBean.getIsSesameAuth() != 0) {
                        startActivity(GoSesameAuthorizedActivity.class, true);           //走芝麻认证
                        return;
                    }
                    if (basicInfoBean.getIsWorkProof() != 0) {
                        startActivity(WorkProofActivity.class, true);                    //走工作证明
                        return;
                    }
                }

                break;
            case 3:
                DMLog.e("抓取成功 手机验证成功");
//                ToastUtil.getInstant().show(getApplicationContext(),"手机验证成功");
                EventBus.getDefault().post(new PhoneAuthEvent(PhoneAuthEvent.PhoneAuthStatue.PHONEAUTH_CRAWLING_SUS));

                if(isConfirml){
                    dismiss();
                    PhoneAuthActivity.this.finish();
                }else {
                    PhoneAuthActivity.this.finish();
//                    if (basicInfoBean.getIsTongDunAuth() != 0) {
//                        startActivity(GoSesameAuthorizedActivity.class, true);           //如果同盾未认证过，走芝麻认证里面的同盾认证接口
//                        return;
//                    }
//                    if (basicInfoBean.getIsSesameAuth() != 0) {
//                        startActivity(GoSesameAuthorizedActivity.class, true);           //走芝麻认证
//                        return;
//                    }
//                    if (basicInfoBean.getIsWorkProof() != 0) {
//                        startActivity(WorkProofActivity.class, true);                    //走工作证明
//                        return;
//                    }

                }
                break;
            case 4:
                dismiss();
                text = "失败";
                ToastUtil.getInstant().show(getApplicationContext(),"失败");
                EventBus.getDefault().post(new PhoneAuthEvent(PhoneAuthEvent.PhoneAuthStatue.PHONEAUTH_FAIL));
                this.finish();
                break;
            case 5:
                text = "用户返回界面";
                EventBus.getDefault().post(new PhoneAuthEvent(PhoneAuthEvent.PhoneAuthStatue.PHONEAUTH_BACK_UI));
                PhoneAuthActivity.this.finish();
                break;
            case 6:
                text = "打开登陆页面,支付宝和淘宝的登陆页面";
                EventBus.getDefault().post(new PhoneAuthEvent(PhoneAuthEvent.PhoneAuthStatue.PHONEAUTH_OPEN_ALIPAY));
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        CrawlerManager.getInstance().unRegisterAllCallBack();
    }

}
